package com.yicong.ants.ui.order;

import android.app.AlertDialog;
import android.app.Dialog;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.PopupWindow;

import androidx.databinding.DataBindingUtil;

import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.order.BillHistoryBean;
import com.yicong.ants.bean.order.VisitorTicketBean;
import com.yicong.ants.databinding.BillDetailActivityBinding;
import com.yicong.ants.databinding.DialogApplyAppealBinding;
import com.yicong.ants.databinding.DialogOrderQrBinding;
import com.yicong.ants.databinding.OrderDealVisitorItemBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.AmapHelper;
import com.yicong.ants.utils.AppUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购买记录详情
 *
 * @author cchao
 * @version 2019-08-23.
 */
public class BillDetailActivity extends BaseTitleBarActivity<BillDetailActivityBinding> implements View.OnClickListener {
    BillHistoryBean mBean;
    List<VisitorTicketBean> mTicketBean;

    @Override
    protected int getLayout() {
        return R.layout.bill_detail_activity;
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Pay_Result_Turn:
                finish();
                break;
        }
    }

    @Override
    protected void initEventAndData() {
        mBean = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON), BillHistoryBean.class);
        setTitleText("门票详情");
        mDataBind.setBean(mBean);
        mDataBind.setClick(this);
        UiHelper.setVisibleElseGone(mDataBind.appealGroup, mBean.getOrder_status() >= 120);
        updateVisitor();
        addTitleMenuItem(R.drawable.ic_bill_menu_tel, v -> {
            String tel = UiHelper.getString(R.string.app_tel);
            if (StringHelper.isNotEmpty(mBean.getTelephone())) {
                tel = mBean.getTelephone();
            }

            AppUtils.jumpToTel(BillDetailActivity.this, tel);
        });
    }

    private void updateVisitor() {
        mDataBind.visitorLinear.removeAllViews();
        UiHelper.setVisibleElseGone(mDataBind.visitorField, CollectionHelper.isNotEmpty(mBean.getVisitors()));
        if (CollectionHelper.isEmpty(mBean.getVisitors())) {
            return;
        }
        for (BillHistoryBean.VisitorsInfo info : mBean.getVisitors()) {
            OrderDealVisitorItemBinding binding = DataBindingUtil.inflate(mLayoutInflater
                , R.layout.order_deal_visitor_item, mDataBind.visitorLinear, false);
            binding.setBean(info);
            if ("sms".equals(mBean.getTicket_type())) {
                binding.ticketLabel.setImageResource(R.drawable.ticket_sms);
            }
            binding.getRoot().setOnClickListener(view -> loadTicketInfo(info));
            mDataBind.visitorLinear.addView(binding.getRoot());
        }
        mDataBind.setBean(mBean);
    }

    /**
     * 加载二维码数据
     */
    private void loadTicketInfo(BillHistoryBean.VisitorsInfo info) {
        // 预约票 进入我的预约页面
        if (4 == mBean.getCategory()) {
            AppHelper.turnToAppointAty(mContext);
            return;
        }
        // 检查 order status
        if (mBean.getOrder_status() != 10) {
            showToast(mBean.getPayStatus());
            return;
        }

        // 如果已经加载好数据
        if (CollectionHelper.isNotEmpty(mTicketBean)) {
            showQrDialog(info);
            return;
        }

        showProgress();
        Map<String, String> map = new HashMap<>();
        map.put("ordersn", mBean.getOrdersn());
//        map.put("id_number", info.getVisitor_id_number());
        addSubscribe(RetrofitHelper.getApis().getTicketQr(map)
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                if (respBean.isCodeFail()) {
                    showToast(respBean.getMsg());
                    return;
                }
                mTicketBean = respBean.getData();
                showQrDialog(info);
            }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    protected void onLoadData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.image:
            case R.id.scenic_name:
                RouterHelper.toScenicDetail(thisActivity, mBean.getScenic_id());
                break;
            case R.id.address:
                PopupWindow mMapPopup = AmapHelper.showNavigatePop(mContext, mBean.getAddress(), mBean.getLatitude(), mBean.getLongitude());
                mMapPopup.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.cancel:
                Router.turnTo(mContext, PayOrderActivity2.class)
                    .putExtra(Constants.Extra.Id, mBean.getScenic_id())
                    .putExtra(Constants.Extra.Ordersn, mBean.getOrdersn())
                    .putExtra(Constants.Extra.Name, mBean.getScenic_name())
                    .putExtra(Constants.Extra.Price, mBean.getTotal_amount())
                    .putExtra(Constants.Extra.Discount, mBean.getDiscount() > 0.00)
                    .start();
                break;
            case R.id.apply_appeal:
                showAppealDialog();
                break;
        }
    }

    Dialog dialog;

    private void showAppealDialog() {
        if (dialog != null) {
            dialog.show();
        }

        DialogApplyAppealBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_apply_appeal, null, false);
        binding.checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            UiHelper.setVisibleElseGone(binding.account, isChecked);
            binding.account.requestFocus();
        });

        binding.appealMobile.setText(UserManager.getUserBean().getUser_name());
        dialog = new AlertDialog.Builder(mContext)
            .setView(binding.getRoot())
            .setPositiveButton("提交申述", (dialog, which) -> {
                if (checkInputFail(binding.appealReason, "请输入申述理由")) {
                    return;
                }
                if (checkInputFail(binding.appealMobile, "请输入申述人手机号")) {
                    return;
                }
                if (binding.checkBox.isChecked() && checkInputFail(binding.account, "请输入收款账号")) {
                    return;
                }

                Map<String, String> map = new HashMap<>();
                map.put("ordersn", mBean.getOrdersn());
                map.put("reason", binding.appealReason.getText().toString());
                map.put("mobile", binding.appealMobile.getText().toString());
                map.put("account", binding.account.getText().toString());

                showProgress();
                addSubscribe(RetrofitHelper.getApis().appealTicketOrder(map)
                    .compose(RxHelper.toMain())
                    .subscribe(respBean -> {
                        hideProgress();
                        if (respBean.isCodeFail()) {
                            return;
                        }
                        showToast(respBean.getMsg());
                        RxBus.get().postEvent(Constants.Event.Update_Order);
                        finish();
                    }, RxHelper.getHideProgressConsumer(this)));
            }).create();
        dialog.show();
    }

    /**
     * 显示游客的二维码
     *
     * @param info 信息
     */
    private void showQrDialog(BillHistoryBean.VisitorsInfo info) {
        // 获取对应 二维码
        String ticketCodeUrl = "";
        for (VisitorTicketBean bean : mTicketBean) {
            if (bean.getId_number().equals(info.getId_number())) {
                // sms
                if ("sms".equals(bean.getTicket_type())) {
                    UiHelper.showConfirmDialog(mContext, "门票信息在您支付时已通过短信发送到您的手机，请查找短信获取门票信息", null);
                    return;
                }

                ticketCodeUrl = bean.getTicket_code_url();
                break;
            }
        }
        // show 二维码
        DialogOrderQrBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_order_qr, null, false);
        binding.name.setText("游客：" + info.getName());

        ImageHelper.loadImage(binding.qrCode, ticketCodeUrl);
        AlertDialog dialog = new AlertDialog.Builder(mContext)
            .setView(binding.getRoot())
            .setCancelable(true)
            .setPositiveButton("确定", (dialog2, which) -> {
                dialog2.dismiss();
            }).create();
        binding.close.setOnClickListener(view -> dialog.dismiss());
        dialog.show();

        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
        dialog.getWindow().setLayout((int) (UiHelper.getScreenWidth() * 4.5f / 5), WindowManager.LayoutParams.WRAP_CONTENT);
//        dialog.getWindow().setAttributes(p);
    }

    boolean checkInputFail(EditText editText, String toast) {
        if (StringHelper.isEmpty(editText)) {
            showToast(toast);
            return true;
        }
        return false;
    }
}
